package edu.ts.crowdfunding.interceptor;

import com.fasterxml.jackson.databind.ser.Serializers;
import edu.ts.crowdfunding.constant.JwtClaimsConstant;
import edu.ts.crowdfunding.context.BaseContext;
import edu.ts.crowdfunding.properties.JwtProperties;
import edu.ts.crowdfunding.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.method.HandlerMethod;

@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断资源
        if (!(handler instanceof HandlerMethod)){
            return true;
        }

        //获取令牌
        String token = request.getHeader(jwtProperties.getTokenName());

        //校验token
        try {
            Claims claims = JwtUtil.praseJWT(jwtProperties.getSecretKey(), token);
            Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            log.info("用户：{} 登录", userId);
            BaseContext.save(userId);
            return true;
        }catch (Exception e){
            log.error("用户登录失败：{}", e.getMessage());
            response.setStatus(401);
            return false;
        }
    }
}
